import React, { Component } from "react";

// connect连接UI组件与redux
import { connect } from "react-redux";

import {
  createAddAction,
  createDeleteAction,
  createAsyncAddAction,
} from "../../redux/actions/count";

class Count extends Component {
  add = () => {
    this.props.add(1);
  };
  delete = () => {
    this.props.delete(1);
  };
  ayncAdd = () => {
    this.props.asyncAdd(2, 1000);
  };

  render() {
    return (
      <div>
        <h2>我是Count组件</h2>
        <div>Count的值：{this.props.count}</div>
        <h3>Person组件的人数为：{this.props.personList.length}</h3>
        <br></br>
        <button onClick={this.add}>+</button>
        <button onClick={this.delete}>-</button>
        <button onClick={this.ayncAdd}>异步＋2</button>
      </div>
    );
  }
}

/**
 * 1、mapStateToProps函数返回一个对象
 * 2、返回的对象中key就作为传递给UI组件props的key，value就作为传递给UI组件props的value
 * 3、mapStateToProps用于传递状态
 */
// function mapStateToProps(store) {
//   return {
//     count: store,
//   };
// }

/**
 * 1、mapDispatchToProps函数返回一个对象
 * 2、返回的对象中key就作为传递给UI组件props的key，value就作为传递给UI组件props的value
 * 3、mapDispatchToProps用于传递操作状态的方法
 * 4、mapDispatchToProps也可以是一个对象
 */
// function mapDispatchToProps(dispatch) {
//   return {
//     add: (data) => dispatch(createAddAction(data)),
//     delete: (data) => dispatch(createDeleteAction(data)),
//     asyncAdd: (data, delay) => dispatch(createAsyncAddAction(data, delay)),
//   };
// }

// 使用connect()()创建并暴露一个Count的容器组件
// 简写方式
export default connect(
  (store) => ({ count: store.count, personList: store.personList }),
  {
    add: createAddAction,
    delete: createDeleteAction,
    asyncAdd: createAsyncAddAction,
  }
)(Count);
